package com.xb.loan.cashier.biz.task;

import com.xb.loan.cashier.biz.util.Configure;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 任务管理线程池
 */
public class TaskManager {
	
	private static final Logger log = LoggerFactory.getLogger(TaskManager.class);
	
	private String taskManagerName;
	
	private ThreadPoolExecutor threadPool = null;
	private LinkedBlockingQueue<Runnable> queue = null;
	private int LIMIT = 1000;
	private int THREADNUM = 10;
	
	
	public TaskManager(String name){
		//任务名称
		this.taskManagerName = name;
		
		if (StringUtils.isNotEmpty(Configure.getStringValue("task.queue.limit." + taskManagerName))) {
			LIMIT = Configure.getIntValue("task.queue.limit." + taskManagerName);
		}
		
		if (StringUtils.isNotEmpty(Configure.getStringValue("task.thread.num." + taskManagerName))) {
			THREADNUM = Configure.getIntValue("task.thread.num." + taskManagerName);
		}
		
		queue = new LinkedBlockingQueue<Runnable>(LIMIT);
		threadPool = new ThreadPoolExecutor(THREADNUM, THREADNUM, 60L, TimeUnit.SECONDS, queue);
		
		log.info("create taskManager " + taskManagerName + " success");
	}
	
	public void addTask(Task task){
		
		if(queue.size() >= LIMIT){
			
			log.info("taskManager:" + taskManagerName + ",queue size over limit");
			return;
		}
		
		threadPool.execute(task);
	}
	
}
